#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Author  :   {Jan__}
# @Time    :   2021/02/05 20:22
import time
import datetime as dt
import os
import sys
import threading

from PyQt5.QtCore import QObject
from PyQt5.QtGui import QTextCursor
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
from Bartender import Bartender
from FileSystem import FileSystem
# from SerialThread import *
from testUI import Ui_Form
class MyUi(QWidget, Ui_Form, QObject):
    # cv_api_signal = pyqtSignal(int)
    # warning_signal = pyqtSignal(str)  # 输出信号，用于告知用户的警告信息
    def __init__(self):
        super(MyUi, self).__init__()    # 分别调用了2个父类的初始化函数
        self.setupUi(self)                          # UI界面控件的初始化
        self.bartender = Bartender()                # Bartender打印引擎
        self.my_file_sys = FileSystem()             # 创建日志
        self.signal_connect()  # 信号与槽函数绑定

    def __del__(self):
        self.bartender.__del__()
    # 信号与槽函数绑定
    def signal_connect(self):
        # 软件启动时列表刷新
        self.scan_printer_list_slot()
        self.scan_btwfile_list_slot()
        # 试打印group
        self.bnt_tryReadFile.clicked.connect(self.try_read_file_slot)
        self.bnt_tryModifySourceContent.clicked.connect(self.try_modify_source_content_slot)
        self.bnt_tryPrint.clicked.connect(self.try_print_slot)
        self.btwFileList_copy.clicked.connect(self.scan_btwfile_list_slot)              # 扫描btw
        self.btwFileList_copy.currentIndexChanged.connect(self.btwfile_changed_slot)    # 切换btw
        self.SubstringList.currentIndexChanged.connect(self.source_changed_slot) #切换数据源
        # 打印机
        self.PrintersList.clicked.connect(self.scan_printer_list_slot)              # 扫描打印机
        # 其他内部信号
        self.bartender.eventSignal.connect(self.bartender_event_slot)  # 打印引擎的事件信息

    def source_changed_slot(self):
        try:
            data_dict = self.bartender.get_data_dict()
            self.lineEdit_sourceContent.setText(data_dict[str(self.SubstringList.currentText())])
            self.my_log_print("试读取数据源成功")
        except Exception as ex:
            print(ex)

    def try_print_slot(self):
        self.try_read_file_slot()
        if self.bartender.btFormat:
            nResult = self.bartender.my_print(self.PrintersList.currentText())
            if nResult == 0:
                self.my_log_print("打印API调用成功")
            elif nResult == 1:
                self.my_log_print("打印API调用失败:超时\n")
            else:
                self.my_log_print("打印API调用失败:其他原因\n")
        else:
            self.my_log_print("试打印失败，未打开标签文件")


    def try_read_file_slot(self, filename=None):
        '''
        读取btw内容的槽函数
        :param filename:
        :return:
        '''
        try:
            # 1.清空UI显示
            self.lineEdit_sourceCount.clear()
            self.SubstringList.clear()
            self.lineEdit_sourceContent.clear()
            # 2.设置btwfile，该函数会自动关闭保存旧的btw文件，然后打开新的btw文件
            res = self.bartender.set_btwfile_using(self.btwFileList_copy.currentText())
            # 3.读取btw文件回显到UI
            if res:
                data_dict = self.bartender.get_data_dict()
                self.lineEdit_sourceCount.setText(str(len(data_dict)))
                for key in data_dict.keys():
                    self.SubstringList.addItem(str(key))
                self.SubstringList.setCurrentIndex(0)
                self.lineEdit_sourceContent.setText(data_dict[str(self.SubstringList.currentText())])
                self.my_log_print("试读取文件成功")
        except Exception as ex:
            print(ex)


    def try_modify_source_content_slot(self):
        '''
        修改数据源数据
        :return:
        '''
        try:
            data_dict = {}
            data_dict[self.SubstringList.currentText()] = str(self.lineEdit_sourceContent.text())
            self.bartender.set_data_dict(data_dict)
            self.my_log_print("完成修改数据源")
        except Exception as ex:
            self.warning_signal.emit("try_modify_source_content_slot 出错！！！" + str(ex))
            print(ex)



    def scan_printer_list_slot(self):

        self.my_log_print("扫描打印机并刷新列表")
        self.PrintersList.clear()
        printers, default_printer = self.bartender.get_printer_list()
        for printer in printers:
            self.PrintersList.addItem(printer, None)
        self.PrintersList.setCurrentText(default_printer)

    def scan_btwfile_list_slot(self, targetfile=None):
        try:
            folder_path = os.getcwd()  # 获取当前路径
            file_list = os.listdir(folder_path + "\\btw\\")
            if targetfile:
                self.my_log_print("寻找："+str(targetfile)+"...")
                time.sleep(0.1)
                for file in file_list:
                    if file == targetfile:
                        self.my_log_print("已找到：" + str(targetfile) + "！")
                        return True
                return False
            if file_list:
                self.my_log_print("扫描btw文件并刷新列表")
                self.btwFileList_copy.clear()
                for file in file_list:
                    if file[-4] == "." and file[-3] == "b" and file[-2] == "t" and file[-1] == "w":
                        # 填充文件列表
                        self.btwFileList_copy.addItem(file, None)
        except Exception as ex:
            # self.warning_signal.emit("scan_btwfile_list_slot 出错！！！" + str(ex))
            print(ex)
    def btwfile_changed_slot(self):
        # 1.清空UI显示
        try:
            self.lineEdit_sourceCount.clear()
            self.SubstringList.clear()
            self.lineEdit_sourceContent.clear()
            self.bartender.close_btwfile()
        except Exception as ex:
            # self.warning_signal.emit("btwfile_changed_slot 出错！！！" + str(ex))
            print(ex)

    def bartender_event_slot(self, msg):
        '''
        打印引擎事件
        :param msg:
        :return:
        '''
        # 监控bartender所有打印事件，当打印机打印完成后，会触发"任务发送"的事件
        self.my_log_print(msg)
        if msg.find("发送") > 0:
            self.my_log_print("打印机打印完成！")

    def my_log_print(self, text):
        self.my_log_print_thread = threading.Thread(target=self.my_log_print_thread_loop, daemon=True, args=(text,))
        self.my_log_print_thread.start()
    def my_log_print_thread_loop(self, text):
        # 获取当前时间
        now_time = dt.datetime.now().strftime('%T') + " : "
        text = now_time + text + '\n'
        # 由于使用append追加文本显示时会自动移除以前的内容，只保留50行
        self.LogPlain.append(text)     # 显示在UI，MaximumBlockCount属性提前在QT中设为50
        self.LogPlain.moveCursor(QTextCursor.End)
        self.my_file_sys.logcat_into_file(text)   # 打印在txt文件

    # 重写app窗口关闭函数
    def closeEvent(self, event):
        reply = QMessageBox.question(self, '退出', "是否要退出程序？", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.No:
            event.ignore()

    def warning_box_slot(self, msg):
        QMessageBox.warning(self, "警告", msg, QMessageBox.Ok)

if __name__ == '__main__':
    try:
        app = QApplication(sys.argv)  # 实例化一个应用对象，sys.argv是一组命令行参数的列表。Python可以在shell里运行，这是一种通过参数来选择启动脚本的方式。
        myshow = MyUi()
        myshow.show()
        sys.exit(app.exec_())  # 确保主循环安全退出
    except Exception as ex:
        print(ex)